/*========= Starting function =========*/
$(function() {
    $(document).ready(function() {
//        $('#list_all_manga').dataTable({
//            "sPaginationType": "full_numbers",
//            "sDom": "<'row-fluid inboxHeader'<'span6'<'dt_actions'>l><'span6'f>r>t<'row-fluid inboxFooter'<'span6'i><'span6'p>>",
//            "iDisplayLength": 25,
//            "asSorting": [[5, "desc"]],
//            "aoColumns": [
//                {"sType": "string"},
//                {"sType": "string"},
//                {"sType": "string"},
//                {"sType": "string"},
//                {"sType": "string"},
//                {"sType": "string"},
//                {"sType": "string"},
//                {"sType": "string"},
//                {"bSortable": false, "sClass": "table-icon nohref"},
//                {"bSortable": false, "sClass": "table-icon nohref"}
//            ]
//        });
        $('.dataTables_length select').chosen();
    });
    manga.init();
});

var manga = (function() {
    var listChapter = new Array();

    function mangaForm_validate() {
        var error = true,
            name = $('#name').val(),
            oname = $('#oname').val(),
            author = $('#author').val(),
            translator = $('#translator').val(),
            desc = $('#desc').val();

        if (!name || name.length > 100) {
            $('#name').addClass('error');
            error = false;
        }

        if (oname.length > 100) {
            $('#oname').addClass('error');
            error = false;
        }

        if (!author || author.length > 100) {
            $('#author').addClass('error');
            error = false;
        }
        
        if (!translator || translator.length > 100) {
            $('#translator').addClass('error');
            error = false;
        }

        if (!desc || desc.length > 2000) {
            $('#desc').addClass('error');
            error = false;
        }

        return error;
    }

    function mangaForm_reset(flag) {
        $('input[type=text]').removeClass('error');
        $('#err_msg').hide().find('.alert').attr('class', 'alert alert-error noMargin');
        if (flag) {
            $('input[type=text]').val('');
            $('#cover').val('');
            $('#err_msg .alert').html('');
        }
    }

    function addManga_handler() {
        $('#add_new_manga_submit').click(function() {
            mangaForm_reset();
            if (mangaForm_validate()) {
                var url = '/manga/ajax_add_new_manga';
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        name: $('#name').val(),
                        oname: $('#oname').val(),
                        author: $('#author').val(),
                        translator: $('#translator').val(),
                        desc: $('#desc').val(),
                        status: $('input:radio[name=status]:checked').val(),
                        cover: $('#cover_hidden').val()
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if (resp.err != 0) {
                            for (var i in resp.msg)
                                $('#' + i).addClass('error');
                            var msg,
                                err = resp.err;
                            switch (err) {
                                case -3:
                                    msg = 'Manga name exist.';
                                    break;
                                default:
                                    msg = 'Something wrong, please check again.';
                            }
                            $('#manga_add_new #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html(msg);
                        } else if (resp.err == 0) {
                            $('#manga_add_new #err_msg').show().find('.alert').attr('class', 'alert alert-success noMargin').html('Successfull.');
                        }
                    }
                });
            } else {
                $('#manga_add_new #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html('Something wrong, please check again.');
            }
            return false;
        });

        $('#add_new_manga_reset').click(function() {
            mangaForm_reset(true);
            return false;
        });
    }

    function uploadCover_handler() {
        var uploader = new plupload.Uploader({
            runtimes: 'html5,browserplus',
            browse_button: 'uploadCover',
            drop_element: 'uploadCover',
            max_file_size: '5mb',
            multipart: true,
            unique_names: true,
            url: '/manga/ajax_upload_manga_cover',
            multi_selection: false,
            filters: [{title: "Image files", extensions: "jpg,gif,png"}]
        });
        uploader.init();
        uploader.bind('FilesAdded', function(up, files) {
            $('.coverErr ul').html('');
            uploader.start();
        });

        uploader.bind('FileUploaded', function(up, file, info) {
            var resp = JSON.parse(info.response);
            if (resp.err == 0 && resp.furl) {
                var url = resp.furl.replace(/\\\//g, '/');
                $('#uploadCover').removeClass('uploadCover').html('<img id="cover" src="' + url + '" />');
                $('#cover_hidden').val(resp.cover_path);
            } else {
                $('.coverErr ul').html('<li>' + resp.msg + '</li>');
            }
        });
    }

    function editManga_handler() {
        $('#edit_manga_submit').click(function() {
            mangaForm_reset();
            if (mangaForm_validate()) {
                var url = '/manga/ajax_edit_manga';
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        id: $('#manga_id').val(),
                        name: $('#name').val(),
                        oname: $('#oname').val(),
                        author: $('#author').val(),
                        translator: $('#translator').val(),
                        desc: $('#desc').val(),
                        cover: $('#cover_hidden').val(),
                        status: $('input:radio[name=status]:checked').val()
                    },
                    dataType: 'json',
                    success: function(resp) {
                        if (resp.err == 0) {
                            $('#manga_slug').val(resp.slug);
                            $('#manga_edit #err_msg').show().find('.alert').attr('class', 'alert alert-success noMargin').html('Successfull.');
                        } else if (resp.err != 0) {
                            for (var i in resp.msg)
                                $('#' + i).addClass('error');
                            var msg, err = resp.err;
                            switch (err) {
                                case -3:
                                    msg = 'Manga name exist.';
                                    break;
                                default:
                                    msg = 'Something wrong, please check again.';
                            }
                            $('#manga_edit #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html(msg);
                        }
                    }
                });
            } else {
                $('#manga_edit #err_msg').show().find('.alert').attr('class', 'alert alert-error noMargin').html('Something wrong, please check again.');
            }
            return false;
        });

        // Remove User
        $('.editRemoveManga').click(function() {
            var id = $(this).attr('id').replace('removeManga_', ''),
                name = $(this).attr('rel'),
                info = '<br/><p>Are you sure to delete the Manga with name <span class="text-error">' + name + '</span>?<br/><br/>';
            showConfirm({
                title: 'Delete user',
                msg: info,
                warning: '<p class="text-warning" align="left">Please understand that this action cannot be reverted. </p>',
                noBt: 'No, not now.',
                yesBt: 'Delete.',
                onYes: function() {
                    var url = '/manga/ajax_remove_manga';
                    $.ajax({type: "POST", url: url, data: {id: id}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                            else if (resp.err == 0) {
                                window.location = '/manga';
                            }
                        }
                    });
                }
            });
            return false;
        });

        //Sort picture
        $("#sortable").sortable({
            update: function(event, ui) {
                $(ui.item[0]).attr('style', '');
            }
        });
    }

    function allManga_hanlder() {
        $('#list_all_manga .removeManga').click(function() {
            var id = $(this).attr('id').replace('removeManga_', ''),
                name = $(this).attr('rel'),
                info = '<br/><p>Are you sure to delete the Manga with name <span class="text-error">' + name + '</span>?<br/><br/>';
            showConfirm({
                title: 'Delete manga',
                msg: info,
                warning: '<p class="text-warning" align="left">Please understand that this action cannot be reverted. </p>',
                noBt: 'No, not now.',
                yesBt: 'Delete.',
                onYes: function() {
                    var url = '/manga/ajax_remove_manga';
                    $.ajax({type: "POST", url: url, data: {id: id}, dataType: 'json',
                        success: function(resp) {
                            if (resp.err != 0)
                                showAlert('Something wrong, please try again later.');
                            else if (resp.err == 0) {
                                var oTable = $('#list_all_manga').dataTable(),
                                    index = $('#mangaRow_' + id).index();
                                oTable.fnDeleteRow(index);
                            }
                        }
                    });
                }
            });
            return false;
        });
    }

    function parseMangaHandler() {
        $('#parseMangaBtn').click(function() {
            var val = $('#parseMangaLink').val(),
                exp = '((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?',
                regex = new RegExp(exp);
            $('#parseManga_errMsg').hide();
            if (!regex.test(val)) {
                $('#parseManga_errMsg').show().find('.alert').html('Link invalid').attr('class', 'alert alert-error noMargin');
                return false;
            }
            $('#parseManga_errMsg').show().find('.alert').html('Parsing Manga Link...').attr('class', 'alert noMargin');
            $.post('/manga/ajax_getManga_chapter_by_link', {
                url: val,
                from: $('#mangaLinkFrom').val(),
                mangaId: $('#manga_id').val()
            }, function(resp) {
                if (resp.err == 0) {
                    var html = '<iframe class="hide" src="' + resp.ifurl + '" width="0" height="0"></iframe>';
                    $('#parseMangaIframe').append(html);
                    $('#parseMangaAction').show();
                    $('#parseManga_errMsg').show().find('.alert').html('Parse Finish. Getting data...').attr('class', 'alert noMargin');
                } else {
                    $('#parseManga_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-error noMargin');
                }

            }, 'json');
            return false;
        });
    }

    function parseMangaResultHandler() {
        $('#mangaResultList a').live('click', function() {
            var a = $(this),
                mangaId = $('#manga_id').val(),
                chapterId = $(this).find('span.label').html(),
                url = $(this).attr('href');
            showConfirm({
                title: 'Parse Chapter',
                msg: 'Are you sure want to parse chapter <strong>' + chapterId + '</strong>?',
                onYes: function() {
                    $(a).find('span.label').removeClass('bSky').addClass('bOlive');
                    $('#parseManga_errMsg').show().find('.alert').html('Parsing chapter ' + chapterId + '...').attr('class', 'alert noMargin');
                    $('#chapter_id').val(chapterId);
                    $('#listImg ul').html('');
                    chapter.createNewChapter(mangaId, chapterId);
                    chapter.parseChapterHandler(url, chapterId, 0, '', function(resp) {
                        if (resp.err == 0) {
                            var html = '<iframe class="hide" src="' + resp.ifurl + '" width="0" height="0"></iframe>';
                            $('#parseIframe').html(html);
                            $('#chapterDetail').show();
                            $('#parseManga_errMsg').show().find('.alert').html('Get HTML Finish. Start to parse image...').attr('class', 'alert noMargin');
                        } else {
                            $('#parseManga_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-error noMargin');
                        }
                    });
                }
            });
            return false;
        });

        $('#parseMangaAction #updateAllChapterCtn').click(function() {
            var list = $('#parseMangaResult #mangaResultList a');
            $('#mangaResultList a span.label').attr('class', 'label noShadow bSky');
            $.each(list, function(i, item) {
                var href = $(item).attr('href'),
                    chapterId = $(item).find('span').html();
                listChapter.push({link: href, chapterId: chapterId});
            });
            recursiveParseLink(listChapter);
            return false;
        });
    }

    function recursiveParseLink(lists) {
        if (!lists.length)
            return;
        var i = lists[0],
            link = i.link,
            chapterId = i.chapterId,
            mangaId = $('#manga_id').val();
        lists.splice(0, 1);
        $('#parseManga_errMsg').show().find('.alert').html('Parsing html of <strong>chapter ' + chapterId + '</strong>...').attr('class', 'alert noMargin');
        chapter.createNewChapter(mangaId, chapterId);
        chapter.parseChapterHandler(link, chapterId, 0, 'manga.truyentranhtuanSaveAllManga', function(resp) {
            if (resp.err == 0) {
                var html = '<iframe class="hide" src="' + resp.ifurl + '" width="0" height="0"></iframe>';
                $('#parseIframe').append(html);
                $('#parseManga_errMsg').show().find('.alert').html('Getting images for <strong>chapter ' + chapterId + '</strong>...').attr('class', 'alert noMargin');
            } else {
                $('#parseManga_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-error noMargin');
            }
        });
    }

    function multiLinkHandler(data, chapterId) {
        $('#parseManga_errMsg').show().find('.alert').html('Uploading Images for chapter <strong>' + chapterId + '</strong>...').attr('class', 'alert noMargin');
        $.post('/manga/ajax_get_image_multi_link', {
            data: data,
            chapterId: chapterId,
            mangaId: $('#manga_id').val(),
            slug: $('#manga_slug').val()
        }, function(resp) {
            if (resp.err == 0) {
                $('#mangaResultList a[rel="' + chapterId + '"] span.label').removeClass('bSky').addClass('bOlive');
                recursiveParseLink(listChapter);
            } else
                $('#parseManga_errMsg').show().find('.alert').html(resp.msg).attr('class', 'alert alert-error noMargin');

        }, 'json');
    }

    return {
        init: function() {
            addManga_handler();
            uploadCover_handler();
            editManga_handler();
            allManga_hanlder();
            parseMangaHandler();
            parseMangaResultHandler();
        },
        truyentranhtuanMessage: function(evt) {
            $('#parseManga_errMsg').hide().find('.alert').html('');
            $('#parseMangaResult').show().find('#mangaResultList').html('');
            evt.sort(function(a, b) {
                var i = a.replace(/\//gi, '').replace($('#manga_slug').val(), ''),
                    j = b.replace(/\//gi, '').replace($('#manga_slug').val(), '');
                return parseInt(i) > parseInt(j);
            })
            for (var i = 0; i < evt.length; i++) {
                var ctn = evt[i].replace(/\//gi, '').replace($('#manga_slug').val(), ''),
                    html = '<a href="http://truyentranhtuan.com' + evt[i] + 'doc-truyen/" onclick="return false;">\
								<span class="label noShadow bSky">' + ctn + '</span>\
							</a>';
                $('#parseMangaResult #mangaResultList').append(html);
            }
        },
        truyentranhtuanSaveAllManga: function(data, chapterId) {
            data = JSON.parse(data);
            for (var i = 0; i < data.length; i++)
                data[i] = 'http://truyentranhtuan.com' + data[i];
            multiLinkHandler(data, chapterId);
        }
    };
})();